package com.jy.rhin.domain.document.filter.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jy.rhin.domain.document.filter.DocumentFilter;
import com.jy.rhin.domain.document.filter.DocumentFilterDescEnum;
import com.jy.rhin.domain.exception.RhinInfraErrorType;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentEntryMapper;
import com.jy.rhin.infra.repo.document.submission.po.DocumentEntryPO;
import com.jy.rhin.infra.uitl.Asserts;
import com.jy.rhin.sdk.dto.document.DocumentContentDto;
import com.jy.rhin.sdk.dto.document.DocumentEntryDto;
import com.jy.rhin.sdk.dto.document.DocumentSubmissionSetDto;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author dhl
 * @date 2022/6/2
 * @Description 文档条目 唯一性校验
 */
@Service
public class DocumentFilter4EntryUniqueness implements DocumentFilter {

    @Resource
    DocumentEntryMapper documentEntryMapper;

    @Override
    public boolean shouldFilter(DocumentSubmissionSetDto submissionSet, List<DocumentContentDto> contentList) {
        return !CollectionUtils.isEmpty(submissionSet.getEntries());
    }

    /**
     * 文档条目 entry 必须唯一
     *
     * @param submissionSet
     * @param contentList
     */
    @Override
    public void doFilter(DocumentSubmissionSetDto submissionSet, List<DocumentContentDto> contentList) {
        List<DocumentEntryDto> entries = submissionSet.getEntries();
        Set<String> entryUniqueIdList = entries.stream().map(DocumentEntryDto::getUniqueId).collect(Collectors.toSet());
        //验证entry在库中是否已经存在
        QueryWrapper<DocumentEntryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(DocumentEntryPO::getUniqueId, entryUniqueIdList);
        Integer count = documentEntryMapper.selectCount(queryWrapper);
        Asserts.equals(0, count, RhinInfraErrorType.ENTRY_UNIQUE_ID_EXISTS);
    }

    @Override
    public DocumentFilterDescEnum filterDesc() {
        return DocumentFilterDescEnum.ENTRY_UNIQUENESS;
    }
}
